<template>
  <div class="index-card">
    <ConditionBox>
      <template #left>
        <div class="title">选择试用期模板</div>
      </template>
      <template #right>
        <!-- <a-button @click="setRules">设置</a-button> -->
      </template>
    </ConditionBox>
    <a-divider />
    <a-form
      :model="performanceInfo"
      style="width: 500px; margin: 0 auto"
      ref="refForm"
      auto-label-width
    >
      <a-form-item
        label="选择试用期考核模板"
        field="performanceAssessmentTemplateName"
        show-colon
      >
        <a-input
          :model-value="templateName"
          style="width: 500px"
          @focus="focus"
          ref="refInput"
        />
      </a-form-item>
      <a-form-item label="考核描述" field="" show-colon>
        <a-textarea
          placeholder="考核描述"
          v-model="performanceInfo.content"
          allow-clear
        />
      </a-form-item>
    </a-form>
  </div>
  <div class="index-card">
    <ConditionBox>
      <template #left>
        <div class="title">试用期考核评分规则</div>
      </template>
      <template #right>
        <a-button @click="setRules">设置</a-button>
      </template>
    </ConditionBox>
    <a-divider />
    <a-table :data="rulesData" :pagination="false" stripe>
      <template #columns>
        <a-table-column title="考核节点" align="center">
          <template #cell="{ rowIndex }">
            <span v-if="rowIndex === 0">考核评价</span>
            <span v-if="rowIndex === 1">员工自评</span>
          </template>
        </a-table-column>
        <a-table-column title="考核总分" align="center">
          <template #cell="">
            {{
              performanceInfo?.upperLimitScore
                ? performanceInfo?.upperLimitScore
                : '不限'
            }}
          </template>
        </a-table-column>
        <a-table-column title="评分计算方式" align="center">
          <template #cell="{}">
            <span v-if="performanceInfo?.scoreCalculation === 2">
              加权计算
            </span>
            <span v-if="performanceInfo?.scoreCalculation === 1">
              加和计算
            </span>
            <span v-if="!performanceInfo?.scoreCalculation">--</span>
          </template>
        </a-table-column>
        <a-table-column title="考核权重" align="center">
          <template #cell="{ rowIndex }">
            <span v-if="rowIndex === 0">
              {{ performanceInfo?.organizationEvaluation }} %
            </span>
            <span v-if="rowIndex === 1">
              <a-input-number
                v-model="performanceInfo.selfEvaluation"
                style="width: 80px"
                @blur="change"
                hide-button
              >
                <template #suffix> % </template>
              </a-input-number>
              <!-- <a-input-number
                v-if="isInput"
                v-focus
                v-model="performanceInfo.selfEvaluation"
                style="width: 80px"
                @blur="change"
                hide-button
              >
                <template #suffix> % </template>
              </a-input-number>
              <span v-else>
                <template
                  v-if="performanceInfo && performanceInfo.selfEvaluation"
                >
                  {{ performanceInfo.selfEvaluation }} %
                </template>
                <template v-else> -- </template>

                <icon-edit
                  style="color: #88b0fd; cursor: pointer"
                  @click="isInput = !isInput"
                />
              </span> -->
            </span>
          </template>
        </a-table-column>
      </template>
    </a-table>
    <!-- <div class="table-div">
      <div class="tr">
        <div class="td">考核节点</div>
        <div class="td">考核总分</div>
        <div class="td">评分计算方式</div>
        <div class="td">考核权重</div>
      </div>
      <div class="tr">
        <div class="td">考核评价</div>
        <div class="td">
          {{
            performanceInfo?.upperLimitScore
              ? performanceInfo?.upperLimitScore
              : '不限'
          }}
        </div>
        <div class="td">
          <span v-if="performanceInfo?.scoreCalculation === 2">加权计算</span>
          <span v-if="performanceInfo?.scoreCalculation === 1">加和计算</span>
          <span v-if="!performanceInfo?.scoreCalculation">--</span>
        </div>
        <div class="td">{{ performanceInfo?.organizationEvaluation }} %</div>
      </div>
      <div class="tr">
        <div class="td">员工自评</div>
        <div class="td">
          {{
            performanceInfo?.upperLimitScore
              ? performanceInfo?.upperLimitScore
              : '不限'
          }}
        </div>
        <div class="td">
          <span v-if="performanceInfo?.scoreCalculation === 2">加权计算</span>
          <span v-if="performanceInfo?.scoreCalculation === 1">加和计算</span>
          <span v-if="!performanceInfo?.scoreCalculation">--</span>
        </div>
        <div class="td">
          <a-input-number
            v-if="isInput"
            v-focus
            v-model="performanceInfo.selfEvaluation"
            style="width: 80px"
            @blur="change"
            hide-button
          >
            <template #suffix> % </template>
          </a-input-number>
          <span v-else>
            <template v-if="performanceInfo">
              {{ performanceInfo.selfEvaluation }} %
            </template>
            <template v-else> -- </template>

            <icon-edit
              style="color: #88b0fd; cursor: pointer"
              @click="isInput = !isInput"
            />
          </span>
        </div>
      </div>
    </div> -->
  </div>
  <a-alert
    v-if="(!weightTotal || weightTotal !== 100) && templateData?.length"
    type="error"
    >考核维度权重的和必须等于100.</a-alert
  >
  <div class="index-card">
    <ConditionBox>
      <template #left>
        <div class="title">考核维度</div>
      </template>
      <template #right></template>
    </ConditionBox>
    <a-divider />
    <a-table :columns="columns" :data="templateData" :pagination="false" stripe>
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #name="{ rowIndex }">
        <a-input style="width: 230px" v-model="templateData[rowIndex].name" />
      </template>
      <template #type="{ rowIndex }">
        {{ getNameByType(templateData[rowIndex].type) }}
      </template>
      <template #weight="{ rowIndex }">
        <span v-if="![5, 6].includes(Number(templateData[rowIndex].type))">
          <a-input-number
            v-model="templateData[rowIndex].weight"
            style="width: 80px"
            hide-button
          >
            <template #suffix> % </template>
          </a-input-number>
        </span>
        <span v-else> 无 </span>
      </template>
      <template #optional="{ record, rowIndex }">
        <!-- <a-tooltip content="编辑">
          <IconFont
            type="icon-edit"
            :size="26"
            :style="{
              marginRight: '10px',
              cursor: 'pointer'
            }"
            @click="record.edit = !record.edit"
          />
        </a-tooltip> -->
        <a-tooltip content="删除" position="left">
          <a-popconfirm
            content="是否确认删除该条数据?"
            @ok="del(record, rowIndex)"
          >
            <icon-font
              type="icon-delete"
              :size="26"
              :style="{
                cursor: 'pointer',
                marginRight: '10px'
              }"
            />
          </a-popconfirm>
        </a-tooltip>
      </template>
    </a-table>
    <a-button v-if="!props.review" type="text" @click="add"
      >新增考核维度</a-button
    >
  </div>
  <ToolsDrawer
    v-model:visible="drawerVisible"
    @submit="submit"
    :data="currData"
    :selectedIndex="selectedIndex"
  />
  <RulesDrawer
    v-model:visible="rulesVisible"
    v-model:data="performanceInfo"
    @change="changeRules"
  />
  <ProbationTemplateModal
    v-model:visible="probationTemplateVisible"
    @save="selectTemplate"
  />
</template>

<script setup lang="ts">
import { PerformanceAssessmentTemplateDimensionality } from '@/apis/management/performance/baseSetting/template/type';
import type { ProbationExamine } from '@/apis/human/base/variationManager/probation/type';
import ToolsDrawer from './ToolsDrawer.vue';
import RulesDrawer from './Tool/RulesDrawer.vue';
import { useVModel } from '@vueuse/core';
import { delExamineTool } from '@/apis/human/base/variationManager/probation';
import { Message } from '@arco-design/web-vue';
import { getProbationToolName } from '@/utils/probation';
import ProbationTemplateModal from './ProbationTemplateModal.vue';
import { GetPerformanceAppraisalTemplateDetails } from '@/apis/management/performance/baseSetting/template';

const props = withDefaults(
  defineProps<{
    data?: PerformanceAssessmentTemplateDimensionality[];
    baseInfo: ProbationExamine;
    review?: boolean;
    deleted: any;
  }>(),
  {
    data: () => [],
    deleted: () => ({})
  }
);
const emit = defineEmits([
  'update:visible',
  'handleOk',
  'update:data',
  'update:deleted'
]);

const templateData = useVModel(props, 'data', emit);
const modelDeleted = useVModel(props, 'deleted', emit);
const performanceInfo = useVModel(props, 'baseInfo', emit);
const rulesColumns = [
  {
    title: '考核节点',
    dataIndex: 'name',
    slotName: 'name',
    align: 'center'
  },
  {
    title: '考核总分',
    dataIndex: 'score',
    slotName: 'score',
    align: 'center'
  },
  {
    title: '评分计算方式',
    dataIndex: 'type',
    slotName: 'type',
    align: 'center'
  },
  {
    title: '考核权重',
    dataIndex: 'weight',
    slotName: 'weight',
    align: 'center'
  }
];
const rulesData = [{}, {}];
const columns = ref<any>([
  {
    title: '序号',
    dataIndex: '',
    slotName: 'index',
    width: 60,
    align: 'center'
  },
  {
    title: '考核维度名称',
    dataIndex: 'name',
    slotName: 'name',
    width: 200,
    align: 'center'
  },
  {
    title: '考核工具',
    dataIndex: 'type',
    slotName: 'type',
    width: 200
  },
  {
    title: '配分/权重',
    dataIndex: 'weight',
    slotName: 'weight',
    width: 160,
    align: 'center'
  }
]);
onMounted(() => {
  if (!props.review) {
    columns.value.push({
      title: '操作',
      dataIndex: 'optional',
      slotName: 'optional',
      width: 130,
      align: 'center'
    });
  }
});
const weightTotal = computed(() => {
  return templateData.value?.reduce((accumulator, currentValue) => {
    const weight = currentValue?.weight ? currentValue?.weight : 0;
    return accumulator + weight;
  }, 0);
});
const currData = ref<PerformanceAssessmentTemplateDimensionality>({});
const drawerVisible = ref(false);
const add = () => {
  editIndex.value = -1;
  currData.value = {};
  drawerVisible.value = true;
};
// 选择维度
const submit = (toolIndex: number[]) => {
  const tempIndex = toolIndex.filter((item) => item !== 5 && item !== 6); //去除没有权重的维度
  const remainder = 100 % tempIndex.length; //取模
  const weight = Math.floor(100 / tempIndex.length); //商
  let isAddRemainder = false; //余数是否已经新增过
  // 取消选择的维度
  selectedIndex.value.forEach((type) => {
    const delIndex = templateData.value.findIndex((item) => item.type === type);
    if (!toolIndex.includes(type)) {
      if (templateData.value[delIndex]?.id) {
        modelDeleted.value.dimensionIds.push(templateData.value[delIndex]?.id);
      }
      templateData.value.splice(delIndex, 1);
    }
  });
  // 新增的维度,平均分配剩余权重
  if (toolIndex.length) {
    toolIndex.forEach((type) => {
      if (!selectedIndex.value.includes(type)) {
        let name = getProbationToolName(type, 1);
        let toolObj = { type, weight: 0, name };
        if (type !== 5 && type !== 6) {
          toolObj.weight = weight;
          if (!isAddRemainder) {
            toolObj.weight += remainder;
            isAddRemainder = true;
          }
        }
        templateData.value.push(toolObj);
      } else {
        const delIndex = templateData.value.findIndex(
          (item) => item.type === type
        );
        if (type !== 5 && type !== 6) {
          templateData.value[delIndex].weight = weight;
          if (!isAddRemainder) {
            templateData.value[delIndex].weight += remainder;
            isAddRemainder = true;
          }
        }
      }
    });
  }
};
const del = async (
  data: PerformanceAssessmentTemplateDimensionality,
  index: number
) => {
  if (!templateData.value?.length) return;
  if (data.id && data.type) {
    modelDeleted.value.dimensionIds.push(data.id);
  }
  templateData.value.splice(index, 1);
};
const editIndex = ref(-1); //编辑项的下标，用以判断新增和编辑，下标小于0是新增数据。大于等于0则是修改此下标的值
const goEdit = (
  data: PerformanceAssessmentTemplateDimensionality,
  index: number
) => {
  editIndex.value = index;
  currData.value = data;
  drawerVisible.value = true;
};
const selectedIndex = computed(() => {
  if (!templateData.value || !templateData.value.length) return [];
  return templateData.value.map((object) => Number(object.type)); //设置已选择的指标
});
const getNameByType = (type?: number) => {
  switch (type) {
    case 1:
      return '关键业绩考核';
    case 2:
      return '能力素质考核';
    case 3:
      return '工作计划考核';
    case 4:
      return '目标与关键成果法';
    case 5:
      return '加减分项';
    case 6:
      return '否决指标法';
    default:
      return '';
  }
};
const rulesVisible = ref(false);
const setRules = () => {
  rulesVisible.value = true;
};
const isInput = ref(false);
const change = () => {
  if (!performanceInfo.value) return;
  if (!performanceInfo.value.selfEvaluation) {
    performanceInfo.value.organizationEvaluation = 0;
  }
  if (!performanceInfo.value.selfEvaluation)
    performanceInfo.value.selfEvaluation = 0;
  performanceInfo.value.organizationEvaluation =
    100 - performanceInfo.value.selfEvaluation;
  isInput.value = false;
};

const changeRules = (data: ProbationExamine) => {
  const { upperLimitType, scoreCalculation, upperLimitScore } = data;
  performanceInfo.value.upperLimitType = upperLimitType;
  performanceInfo.value.scoreCalculation = scoreCalculation;
  performanceInfo.value.upperLimitScore = upperLimitScore;
};
const validate = () => {
  let check = void 0;
  if (weightTotal.value !== 100) {
    Message.error('考核维度权重的和必须等于100.');
    return '考核维度权重的和必须等于100.';
  }

  // if (templateData.value[templateData.value.length - 1].startScore < 0) {
  //   Message.error('分数范围必须大于等于0.');
  //   return {};
  // }
  return check;
};
const refInput = ref();
const probationTemplateVisible = ref(false);
const focus = () => {
  refInput.value.blur();
  probationTemplateVisible.value = true;
};
const templateName = computed(() => {
  const { performanceAssessmentTemplate } = performanceInfo.value;
  if (typeof performanceAssessmentTemplate !== 'object') return '';
  if (!performanceAssessmentTemplate || !performanceAssessmentTemplate.name)
    return '';
  return performanceAssessmentTemplate.name;
});
//选择试用期模板
const selectTemplate = async (templateId: number) => {
  //需要删除所有指标和维度
  // 维度
  performanceInfo.value.personnelAssessmentOptionDimensionality?.forEach(
    (item) => {
      modelDeleted.value.dimensionIds.push(item.id);
    }
  );
  // 能力素养
  performanceInfo.value.personnelAbilityQualityIndexLibrary?.forEach(
    (ability) => {
      modelDeleted.value.ablityIds.push(ability.id);
    }
  );

  // 加减分项
  performanceInfo.value.personnelAddSubtractIndexLibrary?.forEach((item) => {
    modelDeleted.value.addSubtractIds.push(item.id);
  });
  // 关键业绩考核
  performanceInfo.value.personnelKeyPerformanceIndexLibrary?.forEach((item) => {
    modelDeleted.value.keyPerformanceIds.push(item.id);
  });
  //目标
  performanceInfo.value.personnelTargetIndexLibrary?.forEach((target) => {
    modelDeleted.value.targetIds.push(target.id);
  });

  // 否决
  performanceInfo.value.personnelVetoIndexLibrary?.forEach((item) => {
    modelDeleted.value.vetoIds.push(item.id);
  });
  // 工作计划
  performanceInfo.value.personnelWorkPlanIndexLibrary?.forEach((item) => {
    modelDeleted.value.workPlanIds.push(item.id);
  });
  // 使用模板的数据
  if (templateId > 0) {
    const res = await GetPerformanceAppraisalTemplateDetails({
      id: templateId
    });
    // 描述
    performanceInfo.value.content = res.content;
    // 模板名称
    performanceInfo.value.performanceAssessmentTemplateId = templateId;
    performanceInfo.value.performanceAssessmentTemplate = { name: res.name };
    //评分规则
    performanceInfo.value.organizationEvaluation = res.organizationEvaluation;
    performanceInfo.value.scoreCalculation = res.scoreCalculation;
    performanceInfo.value.selfEvaluation = res.selfEvaluation;
    performanceInfo.value.templateType = res.templateType;
    performanceInfo.value.upperLimitScore = res.upperLimitScore;
    performanceInfo.value.upperLimitType = res.upperLimitType;
    //维度
    performanceInfo.value.personnelAssessmentOptionDimensionality =
      res.performanceAssessmentTemplateDimensionality;
    performanceInfo.value.personnelAssessmentOptionDimensionality?.forEach(
      (item) => {
        item.id = void 0;
        item.deletedAt = void 0;
        item.createdAt = void 0;
        item.updatedAt = void 0;
      }
    );
    // 能力素养
    performanceInfo.value.personnelAbilityQualityIndexLibrary =
      res.performanceAbilityQualityIndexLibraryUse;
    performanceInfo.value.personnelAbilityQualityIndexLibrary?.forEach(
      (ability) => {
        ability.id = void 0;
        ability.deletedAt = void 0;
        ability.createdAt = void 0;
        ability.updatedAt = void 0;
        ability.personnelAbilityQualityIndexLibraryScoringStandard =
          ability.performanceAbilityQualityIndexLibraryScoringStandard;
        ability.personnelAbilityQualityIndexLibraryScoringStandard?.forEach(
          (item) => {
            item.id = void 0;
            item.createdAt = void 0;
            item.updatedAt = void 0;
            item.performanceAbilityQualityIndexLibraryUseId = void 0;
          }
        );
      }
    );

    // 加减分项
    performanceInfo.value.personnelAddSubtractIndexLibrary =
      res.performanceAddSubtractIndexLibraryUse;
    performanceInfo.value.personnelAddSubtractIndexLibrary?.forEach((item) => {
      item.id = void 0;
      item.deletedAt = void 0;
      item.createdAt = void 0;
      item.updatedAt = void 0;
    });
    // 关键业绩考核
    performanceInfo.value.personnelKeyPerformanceIndexLibrary =
      res.performanceKeyPerformanceIndexLibraryUse;
    performanceInfo.value.personnelKeyPerformanceIndexLibrary?.forEach(
      (item) => {
        item.id = void 0;
        item.deletedAt = void 0;
        item.createdAt = void 0;
        item.updatedAt = void 0;
      }
    );
    //目标
    performanceInfo.value.personnelTargetIndexLibrary =
      res.performanceTargetIndexLibraryUse;
    performanceInfo.value.personnelTargetIndexLibrary?.forEach((target) => {
      target.id = void 0;
      target.personnelKeyResultsIndexLibrary = [];
      target.performanceKeyResultsIndexLibraryUse?.forEach((result) => {
        result.indexWeight = result.weight;
        result.id = void 0;
        target.personnelKeyResultsIndexLibrary?.push({ ...result });
      });
    });

    // 否决
    performanceInfo.value.personnelVetoIndexLibrary =
      res.performanceVetoIndexLibraryUse;
    performanceInfo.value.personnelVetoIndexLibrary?.forEach((item) => {
      item.id = void 0;
      item.deletedAt = void 0;
      item.createdAt = void 0;
      item.updatedAt = void 0;
    });
    // 工作计划
    performanceInfo.value.personnelWorkPlanIndexLibrary =
      res.performanceWorkPlanIndexLibraryUse;
    performanceInfo.value.personnelWorkPlanIndexLibrary?.forEach((item) => {
      item.id = void 0;
      item.deletedAt = void 0;
      item.createdAt = void 0;
      item.updatedAt = void 0;
    });
  }
};
defineExpose({ validate });
</script>

<style lang="less" scoped>
.index-card {
  border-radius: 10px;

  margin: 20px 0;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  padding: 20px;

  .title {
    font-weight: 600;
    font-size: 18px;
  }
}

.table-div {
  display: flex;
  flex-direction: column;
  width: 100%;

  .tr {
    display: flex;
    height: 60px;
    width: 100%;
    border-top: 1px solid #e5e6eb;
    border-left: 1px solid #e5e6eb;

    .td {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      border-bottom: 1px solid #e5e6eb;
      border-right: 1px solid #e5e6eb;
    }
  }
}
</style>
